/**
 * @Author: aesoper
 * @Description:
 * @File:  map
 * @Version: 1.0.0
 * @Date: 2020/5/19 21:11
 */

package utils

import (
	"github.com/mitchellh/mapstructure"
	"reflect"
)

// 泛类型map转换struct
func WeakMap2Struct(input interface{}, output interface{}, tags ...string) error {
	tag := ""
	if len(tags) >= 1 {
		tag = tags[0]
	}
	decoder, err := mapstructure.NewDecoder(&mapstructure.DecoderConfig{
		TagName:          tag,
		Result:           output,
		WeaklyTypedInput: true,
	})
	if err != nil {
		return err
	}
	return decoder.Decode(input)
}

// 强类型map转换struct
func Map2Struct(input interface{}, output interface{}, tags ...string) error {
	tag := ""
	if len(tags) >= 1 {
		tag = tags[0]
	}
	decoder, err := mapstructure.NewDecoder(&mapstructure.DecoderConfig{
		TagName: tag,
		Result:  output,
	})
	if err != nil {
		return err
	}
	return decoder.Decode(input)
}

func Struct2Map(input interface{}) map[string]interface{} {
	t := reflect.TypeOf(input)
	v := reflect.ValueOf(input)

	var data = make(map[string]interface{})
	for i := 0; i < t.NumField(); i++ {
		data[t.Field(i).Name] = v.Field(i).Interface()
	}
	return data
}
